//
//  DSLoginController.m
//  DSJY
//
//  Created by 冯华强 on 16/9/24.
//  Copyright © 2016年 dsjy. All rights reserved.
//  登录

#import "DSLoginController.h"
#import "DSRegisgerController.h"
#import "MTNavigationController.h"
#import "UIStoryboard+Extension.h"
#import "DSLoginViewModel.h"
#import "DSAccount.h"
#import "GlobalHeader.h"
#import "DSTextField.h"
#import "DSAccountViewModel.h"
#import "MTConst.h"
#import "UIView+Animation.h"
#import "UIWindow+Extension.h"
#import "DSUserNameAndPdViewModel.h"
#import "DSAccount.h"

@interface DSLoginController () <DSRegisgerControllerDelegate>
//拖线属性
@property (weak, nonatomic) IBOutlet UIView *contentView;
//账号文本框
@property (weak, nonatomic) IBOutlet DSTextField *loginIdTextField;
//登录文本框
@property (weak, nonatomic) IBOutlet DSTextField *loginPasswordTextField;
//登录按钮
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
//注册按钮
@property (weak, nonatomic) IBOutlet UIButton *regisgerButton;
//记住账号和密码，默认：是
@property (weak, nonatomic) IBOutlet UIButton *rememberUserNamePdButton;

//登录VM
@property (nonatomic, strong) DSLoginViewModel *loginVM;

@end

@implementation DSLoginController

#pragma mark - 懒加载
- (DSLoginViewModel *)loginVM
{
    if (_loginVM == nil) {
        _loginVM = [[DSLoginViewModel alloc] init];
    }
    return _loginVM;
}

#pragma mark - 系统回调
- (void)viewDidLoad {
    [super viewDidLoad];
    //1.绑定
    [self bindViewModel];
    //2.事件处理
    [self bindEvent];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - 设置UI
- (void)bindViewModel
{
    //0.设置默认为记住账号和密码
    [DSAccountViewModel sharedAccount].rememberUserNamePd = YES;
    
    //1.处理文本框业务逻辑,给文本框赋值(之前登录、注册的用户名和pd)
    DSAccount *account = [DSUserNameAndPdViewModel sharedAccount].account;
    self.loginIdTextField.text = account.name;
    self.loginPasswordTextField.text = account.loginPassword;
    
    //2.给试图模型的帐号和密码绑定信号
    RAC(self.loginVM.account, loginid) = _loginIdTextField.rac_textSignal;
    RAC(self.loginVM.account, loginPassword) = _loginPasswordTextField.rac_textSignal;
    
    //3.设置按钮能否点击
    RAC(_loginButton, enabled) = self.loginVM.loginEndSignal;
}

#pragma mark - 设置事件
- (void)bindEvent
{
    @weakify(self);
    [[_loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        //发送登录请求
        MTLog(@"登录按钮点击");
        [self.loginVM.requestCommand execute:nil];
    }];
    
    //获取发送命令的值
    [self.loginVM.requestCommand.executionSignals.switchToLatest subscribeNext:^(DSAccount *account) {
        @strongify(self);
        //写入用户信息
        //记录密码
        account.loginPassword = self.loginVM.account.loginPassword;
        [MTUserDefaults setObject:account.sessionid forKey:sessionid];
        [DSAccountViewModel sharedAccount].account = account;
        [[DSAccountViewModel sharedAccount] write];
        
        //发送通知
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MTNotificationCenter postNotificationName:DSLoginRegisgerSuccessNote object:nil];
            
            //关闭
            [self dismissViewControllerAnimated:YES completion:nil];
            
            //成功通知
            if ([self.delegate respondsToSelector:@selector(loginControllerDidSuccess:)]) {
                [self.delegate loginControllerDidSuccess:self];
            }
//            [UIWindow switchRootVCToAppDelegateWin];
        });
    }];
    
    //键盘显示
    [[[MTNotificationCenter rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        if (!DSIsLandscape) return ;
        CGFloat top = 135;
        if ([self.loginIdTextField isEditing]) {
            CGFloat f = [self.contentView convertRect:self.loginIdTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }else if([self.loginPasswordTextField isEditing]){
            CGFloat f = [self.contentView convertRect:self.loginPasswordTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }
    }];
    
    //键盘隐藏
    [[[MTNotificationCenter rac_addObserverForName:UIKeyboardWillHideNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        [self.contentView keyboardWillTransform:noti eventViewTop:0 isHide:YES];
    }];
    
    //记住账号和密码
    [[_rememberUserNamePdButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        //记住账号和密码
        self.rememberUserNamePdButton.selected = !self.rememberUserNamePdButton.isSelected;
        [DSAccountViewModel sharedAccount].rememberUserNamePd = self.rememberUserNamePdButton.isSelected;
    }];
}

//注册
- (IBAction)regisgerClick
{
    DSRegisgerController *regisgerVC = (DSRegisgerController *)[UIStoryboard initialVCWithName:@"DSRegisgerController"];
    regisgerVC.title = @"注册";
    regisgerVC.delegate = self;
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:regisgerVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

#pragma mark - <DSRegisgerControllerDelegate>
- (void)regisgerControllerDidSuccess:(DSRegisgerController *)vc
{
    [self dismissViewControllerAnimated:YES completion:nil];
//    [UIWindow switchRootVCToAppDelegateWin];
}

@end
